import { message } from 'antd';

function callChromeBefore(): Promise<any> {
  return new Promise((resolve, reject) => {
    const isChrome = /Chrome\/(\d+)/.test(navigator.userAgent);
    if (!isChrome) {
      message.warning('请使用Chrome浏览器');
      reject('请使用Chrome浏览器');
    }

    // 设置响应监听器
    const listener = (event: MessageEvent) => {
      if (event.data && event.data.type && event.data.type === 'RES_JYZX_EXTENSION_ID') {
        window.removeEventListener('message', listener);
        if (event.data.extensionId) {
          resolve(event.data);
        } else {
          message.warning('没有获取到插件ID');
          reject('没有获取到插件ID');
        }
      }
    };

    window.addEventListener('message', listener);

    window.postMessage(
      {
        type: 'GET_JYZX_EXTENSION_ID',
      },
      '*',
    );

    setTimeout(() => {
      window.removeEventListener('message', listener);
      // message.warning('没有获取到插件ID，请检查是否已安装插件');
      reject('');
    }, 1000);
  });
}

function callChromeFn(chromeExtensionId: string, params: any): Promise<any> {
  return new Promise((resolve, reject) => {
    chrome.runtime.sendMessage(chromeExtensionId, params, (response: any) => {
      if (response.success) {
        // message.success('操作成功');
        resolve('页面已打开');
      } else {
        reject();
      }
    });
  });
}

function logoutAfter(dataId: number) {
  callChromeBefore().then((pluginInfo) => {
    const { extensionId } = pluginInfo;
    callChromeFn(extensionId, {
      type: 'quickLogout',
      dataId,
    });
  });
}

export { callChromeBefore, callChromeFn, logoutAfter };
